package com.kasax.android.arch.bus;

import androidx.lifecycle.MutableLiveData;

import com.kasax.android.arch.Singleton;

import java.util.HashMap;
import java.util.Map;


/**
 * 这条总线用于把任何类中的数据直接传递到activity或是fragment上
 */
public class LiveDataBus {
    //存放订阅者
    private Map<String, MutableLiveData<Object>> map;

    private static final Singleton<LiveDataBus> mLiveDataBusInstance = new Singleton<LiveDataBus>() {
        @Override
        public LiveDataBus create() {
            return new LiveDataBus();
        }
    };

    private LiveDataBus() {
        map = new HashMap<>();

    }

    public static LiveDataBus getInstance() {
        return mLiveDataBusInstance.get();
    }


    //注册订阅者，（存入map）
    public synchronized <T> MutableLiveData<T> with(String key, Class<T> type) {
        if (!map.containsKey(key)) {
            map.put(key, new MutableLiveData<Object>());
        }
        return (MutableLiveData<T>) map.get(key);
    }
}
